<template>
    <div class="notification-list" >
        <van-pull-refresh
          v-model="reFreshLoading"
          @refresh="onRefresh"
          :success-text="successReFresh"
        >
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            v-model:error="error"
            error-text="请求失败，点击重新加载"
            @load="onLoad"
          >
            <notification-item
              v-for="notification in list"
              :key="notification.id"
              :notification="notification"
              class="cell-list"
            ></notification-item>
          </van-list>
        </van-pull-refresh>

    </div>
  </template>
  

  <script>
import { ref,onMounted,onUnmounted } from 'vue';
import { getNotificationChannels } from '../../../api/notification';
import NotificationItem from '../../../components/notification-item/index.vue';
import router from '../../../router';
function useReFerLoad(list, page, reFreshLoading, successReFresh) {
  const onRefresh = async () => {
    try {
      const param = {
        page: page,
        referer: 'load',
      };
      const { data } = await getNotificationChannels(param);
      const results = data.data.records;
      // 追加到列表的顶部
      list.value = results;
      // 关闭下拉刷新状态
      reFreshLoading.value = false;
      successReFresh.value = '刷新成功';
    } catch (err) {
      successReFresh.value = '刷新失败';
      reFreshLoading.value = false;
    }
  };

  return {
    onRefresh,
    reFreshLoading,
    successReFresh,
  };
}
export default {
  components: {
    NotificationItem,
  },
  setup() {
    // 数组，就是列表数据
    const list = ref([]);
    const loading = ref(false);
    // 控制加载状态
    const finished = ref(false);
    let page = 1;
    const successReFresh = ref(false);
    // 数据加载结束状态
    const error = ref(false);

    // 控制下拉刷新的状态
    const reFreshLoading = ref(false);

    // 定义变量记录滚动位置
    let scrollPosition = 0;

    const onLoad = async () => {
      try {
        const param = {
          page: page,
        };
        const { data } = await getNotificationChannels(param);
        const results = data.data.records;
        // 数组
        list.value.push(...results);

        // 获取服务器返回的数据，返回到list中
        // 加载状态结束
        loading.value = false;

        // 是否数据是否全部加载完
        if (Number(data.data.total / 10) >= 1) {
          page = data.data.current + 1;
        } else {
          finished.value = true;
        }
      } catch (err) {
        error.value = true;
        loading.value = false;
      }
    };



    return {
      list,
      onLoad,
      loading,
      finished,
      page,
      error,
      ...useReFerLoad(list, page, reFreshLoading, successReFresh),

    };
  },
};
  </script>



<style scoped>
.cell-list{ 
    min-height: 100px;
}
.notification-list{
    margin-top: 100px;
    height: 530px;
}
</style>